<template>
  <div class="dev-ledger-container">
    <!-- 搜索 + 操作按钮区域 -->
    <div class="search-action-bar">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="设备名称">
          <el-input
            v-model="searchForm.equipmentName"
            placeholder="请输入设备名称"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item label="记录类型">
          <el-select
            v-model="searchForm.recordType"
            placeholder="请选择记录类型"
            clearable
            class="search-input"
          >
            <el-option label="日常检查" value="日常检查" />
            <el-option label="维修" value="维修" />
            <el-option label="更换" value="更换" />
          </el-select>
        </el-form-item>
        <el-form-item label="检修年份">
          <el-input
            v-model.number="searchForm.checkYear"
            placeholder="请输入检修年份"
            clearable
            class="search-input"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格展示区域（使用台账视图实体VLedgerComprehensive） -->
    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="500"
      border
      stripe
      v-loading="tableLoading"
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <el-table-column prop="ledId" label="台账ID" width="100" />
      <el-table-column prop="equipmentName" label="设备全称" width="200" />
      <el-table-column prop="equipmentType" label="设备类型" width="150" />
      <el-table-column prop="recordType" label="记录类型" width="120" />
      <el-table-column prop="creator" label="创建人" width="120" />
      <el-table-column prop="pipeComponent" label="部件名称" width="180" />
      <el-table-column prop="standardThickness" label="标准厚度" width="120" />
      <el-table-column prop="measuredThickness" label="测厚值" width="120" />
      <el-table-column
        prop="thicknessPercentage"
        label="厚度百分比"
        width="140"
      />
      <el-table-column prop="checkYear" label="检修年份" width="120" />
      <el-table-column
        prop="checkDate"
        label="检测日期"
        width="160"
        :formatter="formatDate"
      />
      <el-table-column prop="deviceStatus" label="设备状态" width="120">
        <template #default="scope">
          <span
            :class="{
              'status-normal': scope.row.deviceStatus === '正常',
              'status-attention': scope.row.deviceStatus === '关注',
              'status-warning': scope.row.deviceStatus === '预警',
              'status-replace': scope.row.deviceStatus === '更换',
            }"
          >
            {{ scope.row.deviceStatus }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        prop="recordCreateTime"
        label="创建时间"
        width="160"
        :formatter="formatDate"
      />
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.row)">
            修改
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-bar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageDto.page"
        :page-sizes="[5, 10, 20, 30, 50]"
        :page-size="pageDto.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 新增/修改弹窗（使用台账实体DevLedger） -->
    <el-dialog
      :title="form.ledId ? '修改台账信息' : '新增台账信息'"
      :visible.sync="dialogVisible"
      width="70%"
      :close-on-click-modal="false"
    >
      <!-- 表单使用卡片式布局，优化视觉层次 -->
      <el-card class="form-card">
        <el-form
          :model="form"
          :rules="rules"
          label-width="150px"
          ref="formRef"
          class="form-container"
        >
          <!-- 表单分两列布局优化 -->
          <div class="form-layout">
            <!-- 左侧 -->
            <div class="form-column">
              <!-- 设备ID选择区域 -->
              <el-form-item label="设备ID" prop="deviceId">
                <!-- 第一行：设备ID + 设备名 + 查询按钮 -->
                <div class="device-select-row1">
                  <el-input
                    v-model="form.deviceId"
                    placeholder="设备ID（自动填充）"
                    disabled
                    clearable
                    class="device-id-input"
                  />
                  <el-input
                    v-model="deviceNameInput"
                    placeholder="请输入设备名（支持直接输入）"
                    clearable
                    class="device-name-input"
                  />
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="handleDeviceQuery"
                    class="search-btn"
                    >查询设备</el-button
                  >
                </div>

                <!-- 第二行：设备描述展示栏 -->
                <div class="device-desc-row2" v-if="deviceInfo">
                  <span
                    >设备描述: {{ deviceInfo.deviceDesc || "无描述信息" }}</span
                  >
                </div>
              </el-form-item>

              <el-form-item label="记录类型" prop="ledType">
                <el-select
                  v-model="form.ledType"
                  placeholder="请选择记录类型"
                  clearable
                  class="form-select"
                >
                  <el-option label="日常检查" value="1" />
                  <el-option label="维修" value="2" />
                  <el-option label="更换" value="3" />
                </el-select>
              </el-form-item>

              <el-form-item label="管道标准ID" prop="pipeStaId">
                <div class="pipe-standard-container">
                  <el-input
                    v-model="form.pipeStaId"
                    disabled
                    placeholder="请选择管道标准"
                    class="pipe-id-input"
                  />
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    @click="pipeStandardSelectorVisible = true"
                    class="search-btn"
                    >选择标准</el-button
                  >
                </div>
                <div class="pipe-info" v-if="selectedPipeStandard">
                  <span>部件名称: {{ selectedPipeStandard.pipeName }}</span>
                  <span
                    >管壁最小允许厚度:
                    {{ selectedPipeStandard.pipeValue }}mm</span
                  >
                </div>
              </el-form-item>

              <el-form-item label="预警值/mm" prop="warningValue">
                <el-input
                  v-model.number="form.warningValue"
                  placeholder="预警值"
                  disabled
                  class="form-input"
                />
                <div class="form-hint">
                  取自管道标准:
                  {{ selectedPipeStandard?.pipeName || "未选择管道标准" }}
                </div>
              </el-form-item>

              <el-form-item label="关注值/mm" prop="preWarningValue">
                <el-input
                  v-model.number="form.preWarningValue"
                  placeholder="关注值（默认为：预警值+0.3）"
                  type="number"
                  step="0.01"
                  clearable
                  class="form-input"
                />
                <div class="form-hint">默认值：预警值 + 0.3</div>
              </el-form-item>

              <el-form-item label="检修年份" prop="checkYear">
                <el-input
                  v-model.number="form.checkYear"
                  placeholder="请输入检修年份"
                  clearable
                  class="form-input"
                />
              </el-form-item>

              <el-form-item label="检测日期" prop="checkDate">
                <el-date-picker
                  v-model="form.checkDate"
                  type="date"
                  placeholder="选择检测日期"
                  style="width: 100%"
                  class="form-datepicker"
                />
              </el-form-item>
            </div>

            <!-- 右侧 -->
            <div class="form-column">
              <el-form-item label="宏观检查结果" prop="macrography">
                <el-input
                  v-model="form.macrography"
                  placeholder="请输入宏观检查结果"
                  type="textarea"
                  rows="3"
                  class="form-textarea"
                />
              </el-form-item>

              <el-form-item label="蠕涨值/mm" prop="creepValue">
                <el-input
                  v-model.number="form.creepValue"
                  placeholder="请输入蠕涨值"
                  clearable
                  class="form-input"
                />
              </el-form-item>

              <el-form-item label="测厚值/mm" prop="thicknessValue">
                <el-input
                  v-model.number="form.thicknessValue"
                  placeholder="请输入测厚值"
                  type="number"
                  step="0.01"
                  clearable
                  class="form-input"
                />
              </el-form-item>

              <el-form-item label="厚度百分比" prop="thicknessPercentage">
                <el-input
                  v-model.number="form.thicknessPercentage"
                  placeholder="厚度百分比"
                  disabled
                  class="form-input"
                />
                <div class="form-hint">自动计算: (实测值/标准值)×100%</div>
              </el-form-item>

              <el-form-item label="设备状态" prop="ledDeviceStatus">
                <el-select
                  v-model="form.ledDeviceStatus"
                  placeholder="请选择设备状态"
                  class="form-select"
                >
                  <el-option label="正常" value="zc" />
                  <el-option label="关注" value="gz" />
                  <el-option label="预警" value="yj" />
                  <el-option label="更换" value="gh" />
                </el-select>
              </el-form-item>

              <el-form-item label="台账状态" prop="ledStatus">
                <el-input
                  v-model="form.ledStatus"
                  placeholder="台账状态"
                  disabled
                  class="form-input"
                />
              </el-form-item>

              <el-form-item label="备注信息" prop="ledRemark">
                <el-input
                  v-model="form.ledRemark"
                  placeholder="请输入备注信息"
                  type="textarea"
                  rows="3"
                  class="form-textarea"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
      </el-card>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </div>
    </el-dialog>

    <!-- 管道标准选择器弹窗 -->
    <PipeStandardSelector
      :visible.sync="pipeStandardSelectorVisible"
      @selected="handlePipeStandardSelected"
    />

    <!-- 设备选择弹窗 -->
    <el-dialog
      title="选择设备"
      :visible.sync="deviceSelectorVisible"
      width="60%"
    >
      <el-form :model="deviceForm" :rules="deviceRules" label-width="100px">
        <el-form-item label="设备类型" prop="deviceType">
          <el-select
            v-model="deviceForm.deviceType"
            placeholder="请选择设备类型"
            clearable
            @change="handleDeviceTypeChange"
          >
            <el-option label="管道" value="管道"></el-option>
            <el-option label="吹灰器" value="吹灰器"></el-option>
          </el-select>
        </el-form-item>
        <template v-if="deviceForm.deviceType === '管道'">
          <el-form-item label="模型" prop="model">
            <el-select
              v-model="deviceForm.model"
              placeholder="请选择模型"
              clearable
            >
              <el-option label="后水悬吊管" value="后水悬吊管"></el-option>
            </el-select>
          </el-form-item>
          <!-- 管排区域布局优化 -->
          <el-form-item label="管排" prop="tubeRowInfo">
            <div style="display: flex; align-items: center; gap: 8px">
              <span>从甲到乙</span>
              <span>第</span>
              <el-input
                v-model="deviceForm.tubeRow"
                placeholder="输入管排数字"
                style="width: 120px"
                clearable
              ></el-input>
              <span>管排</span>
            </div>
          </el-form-item>
          <!-- 通道/测点区域布局优化 -->
          <el-form-item label="通道/测点" prop="positionInfo">
            <div style="display: flex; align-items: center; gap: 8px">
              <el-select
                v-model="deviceForm.direction"
                placeholder="请选择方向"
                clearable
                style="width: 120px"
              >
                <el-option label="从前到后" value="从前到后"></el-option>
                <el-option label="从上到下" value="从上到下"></el-option>
              </el-select>
              <span>第</span>
              <el-input
                v-model="deviceForm.position"
                placeholder="输入编号"
                style="width: 120px"
                clearable
              ></el-input>
              <span v-if="deviceForm.direction === '从前到后'">通道</span>
              <span v-if="deviceForm.direction === '从上到下'">测点</span>
            </div>
          </el-form-item>
          <!-- 测点（近远）区域布局优化 -->
          <el-form-item label="测点（近远）" prop="distancePointInfo">
            <div style="display: flex; align-items: center; gap: 8px">
              <span>从近到远</span>
              <span>第</span>
              <el-input
                v-model="deviceForm.distancePoint"
                placeholder="输入测点数字"
                style="width: 120px"
                clearable
              ></el-input>
              <span>测点</span>
            </div>
          </el-form-item>
        </template>
        <template v-if="deviceForm.deviceType === '吹灰器'">
          <el-form-item label="吹灰器编号" prop="sootblowerNo">
            <el-input
              v-model="deviceForm.sootblowerNo"
              placeholder="例如：2-7"
              clearable
            ></el-input>
          </el-form-item>
        </template>
        <el-form-item>
          <div style="display: flex; justify-content: flex-end; gap: 10px">
            <el-button @click="deviceSelectorVisible = false">返回</el-button>
            <el-button type="primary" @click="generateDeviceNameAndQuery"
              >查询</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 引入管道标准选择器组件
import PipeStandardSelector from "../TableOrForms/PipeStandardSelector.vue";

export default {
  components: {
    PipeStandardSelector,
  },
  data() {
    return {
      // 表格数据相关
      tableData: [],
      tableLoading: false,
      total: 0,

      // 分页参数
      pageDto: {
        page: 1,
        size: 10,
        vledger: {}, // 视图查询条件
      },

      // 搜索表单（对应VLedgerComprehensive字段）
      searchForm: {
        equipmentName: "",
        recordType: "",
        checkYear: null,
      },

      // 弹窗相关
      dialogVisible: false,
      pipeStandardSelectorVisible: false,
      deviceSelectorVisible: false,

      // 表单数据
      deviceForm: {
        deviceType: "",
        model: "",
        sootblowerNo: "",
      },
      deviceList: [],
      deviceInfo: null,

      // 管道标准相关
      selectedPipeStandard: null,

      // 表单数据（DevLedger实体字段）
      form: {
        ledId: null,
        deviceId: null,
        ledType: null,
        userCreateId: null,
        userUpdateId: null,
        pipeStaId: null,
        checkYear: null,
        checkDate: null,
        macrography: "",
        creepValue: null,
        thicknessValue: null,
        thicknessPercentage: null,
        preWarningValue: null,
        warningValue: null,
        ledStatus: 1, // 默认待审核
        ledDeviceStatus: "zc", // 默认正常
        ledRemark: "",
      },

      // 设备名输入框（中间字段）
      deviceNameInput: "",
      // 设备选择弹窗表单数据
      deviceForm: {
        deviceType: "", // 设备类型：管道/吹灰器
        model: "", // 管道-模型（如后水悬吊管）
        tubeRow: "", // 管道-管排编号
        direction: "", // 管道-方向（从前到后/从上到下）
        position: "", // 管道-通道/测点编号
        distancePoint: "", // 管道-近远测点编号
        sootblowerNo: "", // 吹灰器-编号
      },
      deviceRules: {
        deviceType: [
          { required: true, message: "请选择设备类型", trigger: "change" },
        ],
        model: [{ required: true, message: "请选择模型", trigger: "change" }],
        tubeRow: [
          { required: false, message: "请输入管排信息", trigger: "blur" },
        ],
        direction: [
          { required: false, message: "请选择方向", trigger: "change" },
        ],
        position: [
          { required: false, message: "请输入通道/测点编号", trigger: "blur" },
        ],
        distancePoint: [
          { required: false, message: "请输入近远测点信息", trigger: "blur" },
        ],
      },

      // 表单验证规则
      rules: {
        deviceId: [
          { required: true, message: "请输入或选择设备ID", trigger: "blur" },
        ],
        ledType: [
          { required: true, message: "请选择记录类型", trigger: "change" },
        ],
        pipeStaId: [
          { required: true, message: "请选择管道标准", trigger: "blur" },
        ],
        checkYear: [
          { required: true, message: "请输入检修年份", trigger: "blur" },
          { type: "number", message: "请输入有效的年份", trigger: "blur" },
        ],
        checkDate: [
          { required: true, message: "请选择检测日期", trigger: "change" },
        ],
        thicknessValue: [
          { required: true, message: "请输入测厚值", trigger: "blur" },
          {
            type: "number",
            message: "请输入有效的数值（支持小数）",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error("测厚值必须大于0"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              // 确保管道规格存在
              if (
                !this.selectedPipeStandard ||
                !this.selectedPipeStandard.pipeSpecification
              ) {
                callback(new Error("请先选择管道规格"));
                return;
              }

              // 从管道规格中提取最大允许值（最后的数字）
              const spec = this.selectedPipeStandard.pipeSpecification;
              const match = spec.match(/(\d+)$/);

              if (!match || !match[1]) {
                callback(new Error("无法从管道规格中提取最大允许值"));
                return;
              }

              const maxValue = Number(match[1]);
              if (isNaN(maxValue)) {
                callback(new Error("管道规格中的最大允许值不是有效的数字"));
                return;
              }

              // 校验测厚值是否超过最大允许值
              if (value > maxValue) {
                callback(new Error(`测厚值不能超过${maxValue}`));
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"], // 同时监听失焦和变化事件
          },
        ],
        preWarningValue: [
          { required: true, message: "请输入关注值", trigger: "blur" },
          {
            type: "number",
            message: "请输入有效的数值（支持小数）",
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              // 确保已选择管道标准
              if (!this.selectedPipeStandard) {
                callback(new Error("请先选择管道标准"));
                return;
              }

              // 确保预警值已设置
              if (
                this.form.warningValue === undefined ||
                this.form.warningValue === null
              ) {
                callback(new Error("未获取到预警值，请检查管道标准"));
                return;
              }

              // 验证关注值不能小于预警值
              if (value < this.form.warningValue) {
                callback(
                  new Error(
                    `关注值不能小于预警值（预警值：${this.form.warningValue}）`
                  )
                );
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              // 确保管道规格存在
              if (
                !this.selectedPipeStandard ||
                !this.selectedPipeStandard.pipeSpecification
              ) {
                callback(new Error("请先选择管道规格"));
                return;
              }

              // 从管道规格中提取最大允许值（最后的数字）
              const spec = this.selectedPipeStandard.pipeSpecification;
              const match = spec.match(/(\d+)$/);

              if (!match || !match[1]) {
                callback(new Error("无法从管道规格中提取最大允许值"));
                return;
              }
              const maxValue = Number(match[1]);
              if (isNaN(maxValue)) {
                callback(new Error("管道规格中的最大允许值不是有效的数字"));
                return;
              }

              // 验证关注值不能大于标准值
              if (value > maxValue) {
                callback(
                  new Error(`关注值不能大于标准值（标准值：${maxValue}）`)
                );
              } else {
                callback();
              }
            },
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  created() {
    // 初始化获取当前用户ID（实际项目中从登录信息获取）
    this.form.userCreateId = localStorage.getItem("userId") || 1;
    this.form.userUpdateId = this.form.userCreateId;
    // console.log(this.form);
    // 初始化加载数据
    this.handleQuery();
  },
  methods: {
    // 日期格式化
    formatDate(row, column) {
      const date = row[column.property];
      if (!date) return "";
      const d = new Date(date);
      return `${d.getFullYear()}-${(d.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${d.getDate().toString().padStart(2, "0")} ${d
        .getHours()
        .toString()
        .padStart(2, "0")}:${d.getMinutes().toString().padStart(2, "0")}`;
    },

    // 分页查询（视图接口）
    handleQuery() {
      this.tableLoading = true;
      // 构建查询参数（对应VLedgerComprehensive）
      this.pageDto.vledger = {
        equipmentName: this.searchForm.equipmentName,
        recordType: this.searchForm.recordType,
        checkYear: this.searchForm.checkYear,
      };

      this.$api.devLedgerApi
        .queryViewsByPage(this.pageDto)
        .then((res) => {
          if (res.data.code === 1) {
            this.tableData = res.data.data.list;
            this.total = res.data.data.total;
          } else {
            this.tableData = [];
            this.total = 0;
            this.$notify.error({
              title: "错误",
              message: res.data.msg || "查询失败",
            });
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "查询异常：网络错误",
          });
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },

    // 重置查询条件
    resetQuery() {
      this.searchForm = {
        equipmentName: "",
        recordType: "",
        checkYear: null,
      };
      this.pageDto.page = 1;
      this.handleQuery();
    },

    // 分页大小变更
    handleSizeChange(size) {
      this.pageDto.size = size;
      this.handleQuery();
    },

    // 当前页变更
    handleCurrentChange(page) {
      this.pageDto.page = page;
      this.handleQuery();
    },

    // 新增
    handleAdd() {
      // 重置表单为新增状态
      this.form = {
        ledId: null,
        ledStatus: 1,
        ledDeviceStatus: "zc",
        userCreateId: this.form.userCreateId,
        userUpdateId: this.form.userCreateId,
      };
      this.deviceInfo = null;
      this.selectedPipeStandard = null;
      this.dialogVisible = true;
    },

    // 编辑
    handleEdit(row) {
      // console.log(row.ledId);
      this.$api.devLedgerApi
        .getById({ id: row.ledId })
        .then((res) => {
          // console.log(res);
          if (res.data.code === 1) {
            this.form = { ...res.data.data };
            // console.log(this.form);

            // 转换日期格式
            if (this.form.checkDate) {
              this.form.checkDate = new Date(this.form.checkDate);
            }
            // 加载管道标准信息
            if (this.form.pipeStaId) {
              this.loadPipeStandardInfo(this.form.pipeStaId);
            }
            // 加载设备信息
            if (this.form.deviceId) {
              this.loadDeviceInfo(this.form.deviceId);
            }
            this.dialogVisible = true;
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.msg || "获取详情失败",
            });
          }
        })
        .catch((e) => {
          console.log(e);
          this.$notify.error({
            title: "错误",
            message: "编辑异常：网络错误",
          });
        });
    },

    // 加载管道标准信息
    loadPipeStandardInfo(pipeStaId) {
      this.$api.pipeStandardApi
        .getById({ id: pipeStaId })
        .then((res) => {
          if (res.data.code === 1) {
            // 存储查询到的管道标准信息
            this.selectedPipeStandard = res.data.data;
            // 回显表单相关字段
            this.form.pipeStaId = res.data.data.pipeStaId; // 管道标准ID
            this.form.warningValue = res.data.data.pipeValue; // 预警值（取自管壁最小允许厚度）
            // 自动计算关注值（默认预警值+0.3，若表单已有值则保留）
            if (!this.form.preWarningValue) {
              this.form.preWarningValue = res.data.data.pipeValue + 0.3;
            }
            // 触发厚度百分比重新计算（基于已有测厚值和管道标准）
            this.calculateThicknessPercentage();
          } else {
            this.$notify.warning({
              title: "提示",
              message: res.data.msg || "未查询到对应管道标准信息",
            });
            // 清空无效数据
            this.selectedPipeStandard = null;
            this.form.pipeStaId = null;
            this.form.warningValue = null;
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "管道标准信息加载失败：网络错误",
          });
        });
    },

    // 加载设备信息（设备名、设备描述）
    loadDeviceInfo(deviceId) {
      this.$api.devDevicesApi
        .queryById({ id: deviceId })
        .then((res) => {
          if (res.data.code === 1) {
            // 存储设备信息用于表单展示
            this.deviceInfo = {
              equipmentName: res.data.data.deviceName, // 设备名称
              deviceDesc: res.data.data.deviceDesc || "无描述信息", // 设备描述（默认值处理）
            };
            // 回显设备名到输入框（方便用户查看）
            this.deviceNameInput = res.data.data.deviceName;
          } else {
            this.$notify.warning({
              title: "提示",
              message: res.data.msg || "未查询到对应设备信息",
            });
            // 清空无效数据
            this.deviceInfo = null;
            this.deviceNameInput = "";
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "设备信息加载失败：网络错误",
          });
        });
    },

    // 删除
    handleDelete(row) {
      this.$confirm(`确定要删除ID为${row.ledId}的台账吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.devLedgerApi
            .deleteById({ id: row.ledId })
            .then((res) => {
              if (res.data.code === 1) {
                this.$notify.success({
                  title: "成功",
                  message: "删除成功",
                });
                this.handleQuery(); // 重新查询
              } else {
                this.$notify.error({
                  title: "错误",
                  message: res.data.msg || "删除失败",
                });
              }
            })
            .catch(() => {
              this.$notify.error({
                title: "错误",
                message: "删除异常：网络错误",
              });
            });
        })
        .catch(() => {
          // 取消删除
          this.$message.info("已取消删除");
        });
    },

    // 表单提交（新增/修改）
    handleSave() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 处理日期格式
          if (this.form.checkDate) {
            this.form.checkDate = new Date(this.form.checkDate);
          }

          // 判断是新增还是修改（根据是否有ledId）
          const isEdit = !!this.form.ledId;
          // 直接使用表单数据，无需额外查询台账实体
          const formData = { ...this.form };

          // 如果是修改操作，设置修改人ID（保持与创建人一致）
          if (isEdit) {
            formData.userUpdateId = formData.userCreateId;
          }

          // 选择对应的API方法
          const apiMethod = isEdit
            ? this.$api.devLedgerApi.edit
            : this.$api.devLedgerApi.addOne;

          // 执行API请求
          apiMethod(formData)
            .then((res) => {
              if (res.data.code === 1) {
                this.$notify.success({
                  title: "成功",
                  message: isEdit ? "修改成功！" : "新增成功！",
                });
                this.dialogVisible = false;
                this.handleQuery(); // 重新查询
              } else {
                this.$notify.error({
                  title: "错误",
                  message: res.data.msg || (isEdit ? "修改失败" : "新增失败"),
                });
              }
            })
            .catch(() => {
              this.$notify.error({
                title: "错误",
                message: "网络异常，请重试",
              });
            });
        }
      });
    },

    // 触发设备查询（点击查询按钮时）
    handleDeviceQuery() {
      if (this.deviceNameInput) {
        // 设备名有数据：直接请求后端
        this.queryDevicesByDeviceName();
      } else {
        // 设备名无数据：打开弹窗
        this.deviceSelectorVisible = true;
        // 重置弹窗表单
        this.deviceForm = {
          deviceType: "",
          model: "",
          tubeRow: "",
          direction: "",
          position: "",
          distancePoint: "",
          sootblowerNo: "",
        };
      }
    },

    // 根据设备名直接查询（设备名有值时）
    queryDevicesByDeviceName() {
      const pageDto = {
        page: 1,
        size: 10,
        devDevices: { deviceName: this.deviceNameInput }, // 对应后端DevDevices的deviceName
      };
      this.sendDeviceQueryRequest(pageDto);
    },

    // 设备类型变化时清空对应字段
    handleDeviceTypeChange(type) {
      if (type === "管道") {
        this.deviceForm.sootblowerNo = ""; // 清空吹灰器字段
      } else if (type === "吹灰器") {
        // 清空管道相关字段
        this.deviceForm.model = "";
        this.deviceForm.tubeRow = "";
        this.deviceForm.direction = "";
        this.deviceForm.position = "";
        this.deviceForm.distancePoint = "";
      }
    },

    // 生成设备名并查询（弹窗内点击查询）
    generateDeviceNameAndQuery() {
      let deviceName = "";
      // 1. 根据设备类型生成设备名
      if (this.deviceForm.deviceType === "管道") {
        // 管道：HSX_GD_管排_位置_近远测点（无值用null）
        const modelCode = "HSX"; // 后水悬吊管固定前缀
        const typeCode = "GD"; // 管道类型前缀
        const tubeRow = this.deviceForm.tubeRow || "null";
        const position = this.deviceForm.position || "null";
        const distancePoint = this.deviceForm.distancePoint || "null";
        deviceName = `${modelCode}_${typeCode}_${tubeRow}_${position}_${distancePoint}`;
      } else if (this.deviceForm.deviceType === "吹灰器") {
        // 吹灰器：CH_编号（无值用null）
        const typeCode = "CH"; // 吹灰器类型前缀
        const sootblowerNo = this.deviceForm.sootblowerNo || "null";
        deviceName = `${typeCode}_${sootblowerNo}`;
      } else {
        this.$message.warning("请选择设备类型");
        return;
      }

      // 2. 用生成的设备名查询后端
      const pageDto = {
        page: 1,
        size: 10,
        devDevices: { deviceName: deviceName }, // 关联后端DevDevices的deviceName
      };
      this.sendDeviceQueryRequest(pageDto);
      // 关闭弹窗
      this.deviceSelectorVisible = false;
      // 回显设备名到输入框
      this.deviceNameInput = deviceName;
    },

    // 通用：发送设备查询请求并处理结果
    sendDeviceQueryRequest(pageDto) {
      this.$api.devDevicesApi
        .queryByPage(pageDto)
        .then((res) => {
          if (res.data.code === 1 && res.data.data.list.length > 0) {
            // 取第一条数据填充
            const firstDevice = res.data.data.list[0];
            this.form.deviceId = firstDevice.deviceId; // 填充设备ID
            this.deviceInfo = {
              equipmentName: firstDevice.deviceName,
              equipmentType: firstDevice.deviceType,
              deviceDesc: firstDevice.deviceDesc, // 设备描述
            };
          } else {
            this.$message.warning("未查询到对应设备");
            this.form.deviceId = "";
            this.deviceInfo = null;
          }
        })
        .catch(() => {
          this.$notify.error({
            title: "错误",
            message: "设备查询失败：网络错误",
          });
        });
    },

    // 处理管道标准选择-仅用于新增时进行管道标准数据的本地存储
    handlePipeStandardSelected(selectedRow) {
      // console.log("接收到的管道标准数据：", selectedRow);
      this.selectedPipeStandard = selectedRow;
      this.form.pipeStaId = selectedRow.pipeStaId;
      this.form.warningValue = selectedRow.pipeValue;
      // 1. 本地存储
      localStorage.setItem("selectedPipeStandard", JSON.stringify(selectedRow));
    },

    // 加载设备信息
    loadDeviceInfo(deviceId) {
      this.$api.devDevicesApi
        .queryById({ id: deviceId })
        .then((res) => {
          if (res.data.code === 1) {
            this.deviceInfo = {
              equipmentName: res.data.data.equipmentName,
              equipmentType: res.data.data.equipmentType,
            };
          }
        })
        .catch((error) => {
          console.error("加载设备信息失败：", error);
        });
    },

    // 计算厚度百分比
    calculateThicknessPercentage() {
      if (
        this.form.thicknessValue &&
        this.selectedPipeStandard &&
        this.selectedPipeStandard.pipeSpecification
      ) {
        // 从 pipeSpecification 中提取最后的数字（如从"Φ63.5×11"中提取"11"）
        const spec = this.selectedPipeStandard.pipeSpecification;
        // 使用正则匹配最后一个数字部分
        const match = spec.match(/(\d+)$/);

        if (match && match[1]) {
          const denominator = Number(match[1]);
          if (denominator > 0) {
            // 避免除以零
            this.form.thicknessPercentage = Number(
              (this.form.thicknessValue / denominator).toFixed(2)
            );
          } else {
            // 处理分母为0的情况
            this.form.thicknessPercentage = null;
            console.warn("管道规格中的厚度值不能为0");
          }
        } else {
          // 处理无法提取数字的情况
          this.form.thicknessPercentage = null;
          console.warn("无法从管道规格中提取厚度值");
        }
      } else {
        this.form.thicknessPercentage = null;
      }
    },
  },
  watch: {
    // 深度监听form.thicknessValue的变化
    "form.thicknessValue": {
      handler(newVal) {
        // 新值有效时触发计算
        if (newVal !== null && !isNaN(Number(newVal))) {
          this.calculateThicknessPercentage();
        }
      },
      immediate: false, // 初始加载时不触发（按需设置）
    },
  },
};
</script>

<style scoped>
.dev-ledger-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
  box-sizing: border-box;
}

.search-action-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-input {
  width: 200px;
}

.pagination-bar {
  margin-top: 20px;
  text-align: right;
}

/* 表单样式优化 */
.form-card {
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-layout {
  display: flex;
  flex-wrap: wrap;
  gap: 25px;
}

.form-column {
  flex: 1;
  min-width: 300px;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 设备选择和管道标准选择区域样式 */
.device-select-container,
.pipe-standard-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.device-id-input,
.pipe-id-input {
  flex: 1;
}

.search-btn {
  white-space: nowrap;
}

.device-info,
.pipe-info {
  margin-top: 8px;
  padding: 5px 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

/* 表单元素样式细化 */
.form-input,
.form-select,
.form-datepicker {
  width: 100%;
}

.form-textarea {
  width: 100%;
  resize: vertical;
}

.form-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

/* 设备选择弹窗样式 */
.device-search-form {
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

/* 状态标签样式 */
.status-normal {
  color: #13ce66;
  background-color: #f0f9eb;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-attention {
  color: #ff7d00;
  background-color: #fff3e0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-warning {
  color: #ff4d4f;
  background-color: #fff1f0;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-replace {
  color: #722ed1;
  background-color: #f9f0ff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

/* 按钮悬停效果 */
.el-button:not(.is-disabled):hover {
  transform: translateY(-2px);
  transition: transform 0.2s ease;
}

/* 设备选择区域布局 */
.device-select-row1 {
  display: flex;
  gap: 10px;
  margin-bottom: 8px;
}
.device-id-input {
  flex: 1;
}
.device-name-input {
  flex: 2;
}
.search-btn {
  width: 120px;
}

/* 设备描述行 */
.device-desc-row2 {
  padding: 8px 12px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  color: #606266;
}

/* 设备选择弹窗内部样式 */
.device-selector-item {
  margin-bottom: 15px;
}
.selector-text {
  margin: 0 5px;
  color: #606266;
}
.short-input {
  width: 100px;
  display: inline-block;
  margin: 0 5px;
}
.short-select {
  width: 120px;
  display: inline-block;
  margin: 0 5px;
}
.normal-input {
  width: 300px;
}
.device-selector-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

/* 穿透 scoped 样式，确保弹窗内容正确渲染 */
::v-deep .el-dialog__body {
  padding: 20px;
}

::v-deep .el-form-item {
  margin-bottom: 18px;
}

::v-deep .el-select,
::v-deep .el-input {
  width: 100%;
}
</style>
